package com.aiju.app;

import com.aiju.app.callback.InitCallback;
import com.aiju.app.config.ConfigManager;
import com.aiju.bean.ErrorCode;
import com.aiju.common.ImageLoader;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import okhttp3.OkHttpClient;

/**
 * @version: V1.0
 * @author: 佐为
 * @date: 2016-12-08 11:15
 * @Description: 项目初始化
 */
public class AppLaunchInit {

    public static final String error = "项目基础信息DataProvider未初始化！";

    private static AtomicBoolean INITED = new AtomicBoolean(false);

    /**
     * 项目初始化
     *
     * @param dataProvider
     * @param callback
     */
    public static void init(IDataProvider dataProvider, InitCallback callback) {
        if (INITED.compareAndSet(false, true)) {
            if (dataProvider == null || dataProvider.getContext() == null) {
                if (callback != null) {
                    callback.onFailure(ErrorCode.INIT_ERROR, error);
                }
                return;
            }
            try {
                initialize(dataProvider);
                if (callback != null) {
                    callback.onSuccess();
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (callback != null) {
                    callback.onFailure(ErrorCode.INIT_ERROR, e.getMessage());
                }
            }
        }
    }

    /**
     * 日志初始化,缓存初始化，目录初始化，系统设置初始化等
     *
     * @param dataProvider
     */
    private static void initialize(IDataProvider dataProvider) {
        DataProviderManager.setDataProvider(dataProvider);
        ImageLoader.init(DataProviderManager.getContext());
        ConfigManager.getInstance().init();
        ZXingLibrary.initDisplayOpinion(DataProviderManager.getContext());
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LoggerInterceptor(ConfigManager.DEBUG_HTTP_TAG))
                .connectTimeout(30000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                .build();
        OkHttpUtils.initClient(okHttpClient);
    }
}
